/* eslint-disable no-nested-ternary */
import utils, { NameSpace } from 'utils';
import exceed from 'utils/apimap';
import { uilessRequest } from '@alife/yunxiao-common';
import track from 'utils/track';
import { getIntroPointState } from 'api';
import { Message } from '@teamix/ui';

const ns = NameSpace('group');
export const SEARCH_CHANGE_FEEDBACK = ns('SEARCH_CHANGE_FEEDBACK');
export const SEARCH_IS_FINISHED = ns('SEARCH_IS_FINISHED');
export const SEARCH_CONFETTI_CHANGE = ns('SEARCH_CONFETTI_CHANGE');
export const SEARCH_EDITOR_FOCUS_OBJ = ns('SEARCH_EDITOR_FOCUS_OBJ');
export const SEARCH_DSL_ERROR_MESSAGE_CHANGE = ns('SEARCH_DSL_ERROR_MESSAGE_CHANGE');
export const SEARCH_RIGHT_GRAMMAR_COUNT_LIST = ns('SEARCH_RIGHT_GRAMMAR_COUNT_LIST');
export const SEARCH_HEADER_INPUT_STATUS_CHANGE = ns('SEARCH_HEADER_INPUT_STATUS_CHANGE');
export const SEARCH_HEADER_MODE_STATUS = ns('SEARCH_HEADER_MODE_STATUS');
export const HEAD_INPUT_STRING_ONE_TIPS = ns('HEAD_INPUT_STRING_ONE_TIPS');
export const HEADER_SELECT_ON_CHANGE = ns('HEADER_SELECT_ON_CHANGE');
export const SEARCH_HEADER_INPUT_CHANGE = ns('SEARCH_HEADER_INPUT_CHANGE');
export const SEARCH_LEFT_CON_DATA = ns('SEARCH_LEFT_CON_DATA');
export const SEARCH_LEFT_CON_LOADING = ns('SEARCH_LEFT_CON_LOADING');
export const SEARCH_LEFT_SELECT_VALUE = ns('SEARCH_LEFT_SELECT_VALUE');
export const SEARCH_LEFT_DATA_PAGIATION = ns('SEARCH_LEFT_DATA_PAGIATION');
export const SEARCH_ROW_COL_SPAN = ns('SEARCH_ROW_COL_SPAN');
export const SEARCH_GET_MIDDLE_DATA = ns('SEARCH_GET_MIDDLE_DATA');
export const SEARCH_MIDDLE_LOADING = ns('SEARCH_MIDDLE_LOADING');
export const SEARCH_SET_FILTER_VALUE = ns('SEARCH_SET_FILTER_VALUE');
export const SEARCH_SET_SEARCH_TYPE = ns('SEARCH_SET_SEARCH_TYPE');
export const SEARCH_SET_SEARCH_LANGUAGE = ns('SEARCH_SET_SEARCH_LANGUAGE');
export const SEARCH_MR_STATE = ns('SEARCH_MR_STATE');
export const SEARCH_MR_SELECT_DATA = ns('SEARCH_MR_SELECT_DATA');
export const SEARCH_CODE_STORE_HOUSE_DATA = ns('SEARCH_CODE_STORE_HOUSE_DATA');
export const SEARCH_CODE_STORE_HOUSE_TYPE_VALUE = ns('SEARCH_CODE_STORE_HOUSE_TYPE_VALUE');
export const SEARCH_CODE_REPO_SELECT_VALUE = ns('SEARCH_CODE_REPO_SELECT_VALUE');
export const SEARCH_CODE_LEFT_LIST_DATA = ns('SEARCH_CODE_LEFT_LIST_DATA');

let oneFlag = true;

export const changeFeedback = (data) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_CHANGE_FEEDBACK,
      data,
    });
  };
};

export const changeConfettiShow = (data) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_CONFETTI_CHANGE,
      data,
    });
  };
};

// 初始化ediot可以聚焦的dom对象
export const changeEditorFocusObj = (data) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_EDITOR_FOCUS_OBJ,
      data,
    });
  };
};

export const changeModeStatus = (value) => {
  const data = value === 'ordinary' ? 'grammar' : 'ordinary';
  return (dispatch) => {
    dispatch({
      type: SEARCH_HEADER_MODE_STATUS,
      data,
    });
  };
};

export const headerSelectOnChange = (value, flag) => {
  return (dispatch) => {
    dispatch({
      type: HEADER_SELECT_ON_CHANGE,
      data: value,
    });
    !flag && dispatch(getSearchInputData());
    !flag && dispatch(getsearchCountAndLanguage(true));
  };
};

// https://yuque.antfin.com/aone/code+voice/ayk28n#rUz68
export const getSearchInputData = (type) => {
  return (dispatch, getState) => {
    const value = getState().search.root;
    if (value.headerInputValue.length === 1) {
      dispatch({
        type: HEAD_INPUT_STRING_ONE_TIPS,
        data: true,
      });
    } else {
      value.rowSpanCol?.middleState && dispatch(closeMiddleMode());
      dispatch({
        type: SEARCH_LEFT_CON_LOADING,
        data: true,
      });
      dispatch({
        type: HEAD_INPUT_STRING_ONE_TIPS,
        data: false,
      });
      // value.headerInputValue = value.headerInputValue.replace(/^ *(.*?) *$/, '$1');
      value.headerInputValue = value.headerInputValue.trimEnd();
      if (value.headerInputValue && value.headerModeStatus === 'ordinary') {
        exceed
          .fetch({
            api: 'search_codeup_search',
            params: {
              type: type || value.searchType,
            },
            data: {
              keyword: value.headerInputValue.trim(),
              language: value.searchLanguageValue || '',
              file_path: {},
              repo_path: {
                name: '',
                value:
                  value.searchCodeHouseType.isRegexp === true
                    ? value.searchCodeHouseType.value
                    : value.searchCodeHouseType.isRegexp === false
                    ? value.searchCodeHouseType.value.join(',')
                    : '',
                operator_type: value.searchCodeHouseType.value ? 'equal' : '',
                match_type:
                  value.searchCodeHouseType.isRegexp === true
                    ? 'regex'
                    : value.searchCodeHouseType.value
                    ? 'term'
                    : '',
              },
              is_code_block: false,
              order: value.leftMatchSelectValue === 'default' ? 'default' : 'updated_at',
              sort: value.leftMatchSelectValue === 'updated_at_asc' ? 'asc' : 'desc',
              scope: value.headerSelectValue,
              page: value.leftDataPage.page || 1,
              page_size: value.leftDataPage.page_size || 10,
              creator_id:
                value.searchType === 'mr'
                  ? value.searchRightMrValue.establish || ''
                  : value.searchType === 'repo'
                  ? value.searchVodeRepoSelectValue.creatorId
                  : '',
              reviewer_id: value.searchType === 'mr' ? value.searchRightMrValue.review || '' : '',
              state: value.searchType === 'mr' ? value.searchRightMrValue.state || '' : '',
              // eslint-disable-next-line max-len
              visibility:
                value.searchType === 'repo' && value.searchVodeRepoSelectValue?.visibility
                  ? value.searchVodeRepoSelectValue.visibility - 0
                  : '',
            },
          })
          .then((result) => {
            value?.editorFocusObj?.setPosition({
              column: value.headerInputValue.length + 1,
              lineNumber: 1,
            }); // 回车之后光标回到指定位置
            track({
              action: 'search_result_count',
              page: 'Search-Page',
              type:
                value.searchType === 'code'
                  ? 'code_snippet'
                  : value.searchType === 'repo'
                  ? 'code_repo'
                  : value.searchType === 'commit'
                  ? 'code_commit'
                  : 'code_mr', // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
              control:
                result.amount === 0
                  ? 'default'
                  : result.amount <= 10
                  ? 'less'
                  : result.amount <= 100
                  ? 'middle'
                  : 'large', // default:还没有搜索，none:当前搜索结果=0，less:0<当前搜索结果<=10，middle:10<当前搜索结果<=100，large:当前搜索结果 > 100
            });
            dispatch({
              type: SEARCH_LEFT_CON_DATA,
              data: value.searchType === 'commit' ? SearchInputDataFilter(result) : result,
            });
            dispatch({
              type: SEARCH_LEFT_CON_LOADING,
              data: false,
            });
          })
          .fail(() => {
            dispatch({
              type: SEARCH_LEFT_CON_LOADING,
              data: false,
            });
          });
      } else if (value.headerModeStatus === 'grammar' && value.headerInputValue) {
        getIntroPointState('codeup_common_pop_up', {
          booth_code: 'search_page_feed_back',
        }).then((res) => {
          if (!utils.getCachedData('grammarShow') && !value.dslErrorMessage) {
            setTimeout(() => {
              utils.setCachedData('grammarShow', true);
              Message.show({ title: '🎉 欢迎体验语法搜索功能！', iconType: ' ' });
              dispatch(changeConfettiShow(true));
              setTimeout(() => {
                dispatch(changeConfettiShow(false));
              }, 2000);
            }, 150);
          }
          if (res.state) {
            dispatch({
              type: SEARCH_CHANGE_FEEDBACK,
              data: {
                isShow: true,
                planId: res.result.planId,
              },
            });
          } else {
            dispatch({
              type: SEARCH_CHANGE_FEEDBACK,
              data: {
                isShow: false,
                planId: '',
              },
            });
          }
        });
        if (value.searchType === 'commit') {
          value.searchType = 'commits';
        } else if (value.searchType === 'mr') {
          value.searchType = 'codereview';
        }
        exceed
          .fetch({
            api: 'search.dsl_query',
            data: {
              search_type: value.searchType,
              dsl_query_string: value.headerInputValue.trim(),
              page: value.leftDataPage.page,
              page_size: 10,
              order: value.leftMatchSelectValue === 'default' ? 'default' : 'updated_at',
              sort: value.leftMatchSelectValue === 'updated_at_asc' ? 'asc' : 'desc',
            },
          })
          .then((result) => {
            track({
              action: 'dsl_search_result_count',
              page: 'Search-Page',
              type:
                value.searchType === 'code'
                  ? 'code_snippet'
                  : value.searchType === 'repo'
                  ? 'code_repo'
                  : value.searchType === 'commit'
                  ? 'code_commit'
                  : 'code_mr', // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
              control:
                result.amount === 0
                  ? 'default'
                  : result.amount <= 10
                  ? 'less'
                  : result.amount <= 100
                  ? 'middle'
                  : 'large', // default:还没有搜索，none:当前搜索结果=0，less:0<当前搜索结果<=10，middle:10<当前搜索结果<=100，large:当前搜索结果 > 100
            });
            dispatch({
              type: SEARCH_DSL_ERROR_MESSAGE_CHANGE,
              data: null,
            });
            dispatch({
              type: SEARCH_LEFT_CON_DATA,
              data: result,
            });
            dispatch({
              type: SEARCH_LEFT_CON_LOADING,
              data: false,
            });
          })
          .fail((e) => {
            const errMessage = JSON.parse(e.response);
            dispatch({
              type: SEARCH_DSL_ERROR_MESSAGE_CHANGE,
              data: errMessage,
            });
            const result = {
              amount: 0,
              list: [],
            };
            dispatch({
              type: SEARCH_LEFT_CON_DATA,
              data: result,
            });
            dispatch({
              type: SEARCH_LEFT_CON_LOADING,
              data: false,
            });
          });
      } else {
        dispatch({
          type: SEARCH_LEFT_CON_DATA,
          data: [],
        });
        dispatch({
          type: SEARCH_LEFT_CON_LOADING,
          data: false,
        });
      }
    }
  };
};
const SearchInputDataFilter = (data) => {
  const newArray =
    data.list &&
    data.list.length > 0 &&
    data.list.map((va) => {
      if (va.highlightTextMap.commitMessage && va.highlightTextMap.commitMessage.includes('mark')) {
        const artstr = va.highlightTextMap.commitMessage.split('\n');
        if (artstr.length > 1) {
          artstr.shift();
        }
        if (artstr.join('').includes('mark')) {
          return {
            ...va,
            isMsgDescVisible: true,
          };
        }
      }
      return {
        ...va,
      };
    });
  return {
    amount: data.amount,
    list: newArray || [],
  };
};

export const setLeftDataPagination = (value, flag) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_LEFT_DATA_PAGIATION,
      data: {
        page: value,
        page_size: 10,
      },
    });
    !flag && dispatch(getSearchInputData());
    !flag && dispatch(getsearchCountAndLanguage());
  };
};

export function getSearchOnChange(value) {
  return (dispatch) => {
    dispatch({
      type: SEARCH_HEADER_INPUT_CHANGE,
      data: value,
    });
  };
}

export const getSearchData = () => {
  return (dispatch) => {
    dispatch(getSearchInputData());
    dispatch(getsearchCountAndLanguage());
  };
};

export function setMatchSelectValue(value) {
  return (dispatch) => {
    dispatch({
      type: SEARCH_LEFT_SELECT_VALUE,
      data: value,
    });
    dispatch(getSearchInputData());
    dispatch(getsearchCountAndLanguage(true));
  };
}

export const setRoWColSpan = (value, headerModeStatus) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_ROW_COL_SPAN,
      data: {
        left: '8',
        right: '0',
        middle: '16',
        middleState: true,
        previewDocId: value,
      },
    });
    dispatch(getMiddleData(value, headerModeStatus));
  };
};

export const setRowColSpanRight = (type) => {
  return (dispatch, getState) => {
    const value = getState().search.root;
    dispatch({
      type: SEARCH_ROW_COL_SPAN,
      data: {
        left: '8',
        right: !type ? '4' : '0',
        middle: !type ? '12' : '16',
        middleState: true,
        previewDocId: value.rowSpanCol.previewDocId,
        rightOpen: !type,
      },
    });
  };
};

const getsearchCountAndLanguage = (flag = false, valueCount = -1) => {
  return async (dispatch, getState) => {
    const value = getState().search.root;
    // value.headerInputValue = value.headerInputValue.replace(/^ *(.*?) *$/, '$1');
    value.headerInputValue = value.headerInputValue.trimEnd();
    if (value.headerInputValue && value.headerModeStatus === 'ordinary') {
      const storeFilter = value.searchFilterValue
        ?.filter((va, ids) => {
          return (
            va.inputValue !== value.headerInputValue ||
            va.fiterCount.totoalCount === undefined ||
            flag ||
            ids === 0
          );
        })
        .map((val) => val.type);
      const filterArray = !storeFilter ? ['code', 'repo', 'mr', 'commit'] : storeFilter;
      const allCountRequest = ['code', 'repo', 'mr', 'commit'].map(async (info) => {
        const res = (await requestCount(info, value)) || {};
        return res;
      });
      const allStaggregate =
        value.searchType === 'code' && valueCount < 0 ? await requeStaggregateCount(value) : [];
      const result = await Promise.all(allCountRequest);
      const searchCountMap = ['code', 'repo', 'mr', 'commit'].map((va) => {
        const idsx = filterArray && filterArray.findIndex((val) => val === va);
        if (va === value.searchType && value.searchType === 'code') {
          const res = Object.entries(allStaggregate).map(([key, val]) => {
            return {
              [key]: val,
            };
          });
          return {
            type: va,
            fiterCount:
              idsx >= 0
                ? result[idsx]
                : value.searchLanguageValue && valueCount >= 0
                ? {
                    languageAggMap: null,
                    totoalCount: valueCount,
                  }
                : findStoreCountValue(value.searchFilterValue, va),
            languageCount:
              value.searchLanguageValue && valueCount >= 0
                ? findStoreLanguaCount(value.searchFilterValue, 'code')
                : res,
            inputValue: value.headerInputValue,
          };
        } else {
          return {
            type: va,
            fiterCount: idsx >= 0 ? result[idsx] : findStoreCountValue(value.searchFilterValue, va),
            inputValue: value.headerInputValue,
          };
        }
      });
      dispatch({
        type: SEARCH_SET_FILTER_VALUE,
        data: searchCountMap || [],
      });
      if (oneFlag === true) {
        if (result[0]?.totoalCount === 0) {
          const valuess = result.findIndex((va) => va.totoalCount > 0);
          const name =
            valuess === 0
              ? 'code'
              : valuess === 1
              ? 'repo'
              : valuess === 2
              ? 'mr'
              : valuess === 3
              ? 'commit'
              : undefined;
          name && dispatch(setSearchType(name));
        }
        oneFlag = false;
      }
    } else if (value.headerInputValue && value.headerModeStatus === 'grammar') {
      const allCountRequest = ['code', 'repo', 'commits', 'codereview'].map(async (type) => {
        const res =
          (await searchDslCount({
            search_type: type,
            dsl_query_string: value.headerInputValue.trim(),
          })) || {};
        return res;
      });
      const result = await Promise.all(allCountRequest);
      dispatch({
        type: SEARCH_RIGHT_GRAMMAR_COUNT_LIST,
        data: result || [],
      });
      if (oneFlag === true) {
        if (result[0]?.totoalCount === 0) {
          const valuess = result.findIndex((va) => va.totoalCount > 0);
          const name =
            valuess === 0
              ? 'code'
              : valuess === 1
              ? 'repo'
              : valuess === 2
              ? 'mr'
              : valuess === 3
              ? 'commit'
              : undefined;
          name && dispatch(setSearchType(name));
        }
        oneFlag = false;
      }
    } else {
      dispatch({
        type: SEARCH_SET_FILTER_VALUE,
        data: null,
      });
    }
  };
};

const findStoreLanguaCount = (data, type) => {
  const value = data.filter((va) => va.type === type);
  return value ? value[0].languageCount : [];
};

const findStoreCountValue = (data, type) => {
  const value = data.filter((va) => va.type === type);
  return value
    ? value[0].fiterCount
    : {
        languageAggMap: null,
        totoalCount: 0,
      };
};

const requeStaggregateCount = async (value) => {
  // value.headerInputValue = value.headerInputValue.replace(/^ *(.*?) *$/, '$1');
  value.headerInputValue = value.headerInputValue.trimEnd();
  const result = await exceed.fetch({
    api: 'search_root_codeup_aggregate_num',
    data: {
      keyword: value.headerInputValue.trim(),
      page: value.leftDataPage.page || 1,
      page_size: value.leftDataPage.page_size || 10,
      file_path: {},
      repo_path: {
        name: '',
        value:
          value.searchCodeHouseType.isRegexp === true
            ? value.searchCodeHouseType.value
            : value.searchCodeHouseType.isRegexp === false
            ? value.searchCodeHouseType.value.join(',')
            : '',
        operator_type: value.searchCodeHouseType.value ? 'equal' : '',
        match_type:
          value.searchCodeHouseType.isRegexp === true
            ? 'regex'
            : value.searchCodeHouseType.value
            ? 'term'
            : '',
      },
      language: '',
      is_code_block: false,
      order: value.leftMatchSelectValue === 'default' ? 'default' : 'updated_at',
      sort: value.leftMatchSelectValue === 'updated_at_asc' ? 'asc' : 'desc',
      scope: value.headerSelectValue,
      creator_id:
        value.searchType === 'mr'
          ? value.searchRightMrValue.establish || ''
          : value.searchType === 'repo'
          ? value.searchVodeRepoSelectValue.creatorId
          : '',
      reviewer_id: value.searchType === 'mr' ? value.searchRightMrValue.review || '' : '',
      state: value.searchType === 'mr' ? value.searchRightMrValue.state || '' : '',
      visibility:
        value.searchType === 'repo' && value.searchVodeRepoSelectValue?.visibility
          ? value.searchVodeRepoSelectValue.visibility - 0
          : '',
    },
    params: {
      type: value.searchType,
      group_by: 'language',
    },
  });
  return result.languageAggMap;
};

const requestCount = (data, value) => {
  // value.headerInputValue = value.headerInputValue.replace(/^ *(.*?) *$/, '$1');
  value.headerInputValue = value.headerInputValue.trimEnd();
  return exceed.fetch({
    api: 'search_root_codeup_filter_statistics',
    data: {
      keyword: value.headerInputValue.trim(),
      page: value.leftDataPage.page || 1,
      page_size: value.leftDataPage.page_size || 10,
      file_path: {},
      repo_path: {
        name: '',
        value:
          value.searchCodeHouseType.isRegexp === true
            ? value.searchCodeHouseType.value
            : value.searchCodeHouseType.isRegexp === false
            ? value.searchCodeHouseType.value.join(',')
            : '',
        operator_type: value.searchCodeHouseType.value ? 'equal' : '',
        match_type:
          value.searchCodeHouseType.isRegexp === true
            ? 'regex'
            : value.searchCodeHouseType.value
            ? 'term'
            : '',
      },
      language: value.searchLanguageValue || '',
      is_code_block: false,
      order: value.leftMatchSelectValue === 'default' ? 'default' : 'updated_at',
      sort: value.leftMatchSelectValue === 'updated_at_asc' ? 'asc' : 'desc',
      scope: value.headerSelectValue,
      creator_id: value.searchType === 'mr' ? value.searchRightMrValue.establish || '' : '',
      reviewer_id: value.searchType === 'mr' ? value.searchRightMrValue.review || '' : '',
      state: value.searchType === 'mr' ? value.searchRightMrValue.state || '' : '',
      visibility:
        value.searchType === 'repo' && value.searchVodeRepoSelectValue?.visibility
          ? value.searchVodeRepoSelectValue.visibility - 0
          : '',
    },
    params: {
      type: data,
    },
  });
};

export const setSearchType = (value) => {
  return (dispatch, getState) => {
    const stateData = getState().search.root;
    dispatch({
      type: SEARCH_SET_SEARCH_TYPE,
      data: value,
    });
    if (stateData.rowSpanCol.middleState) {
      dispatch(closeMiddleMode());
    }
    if (
      stateData.searchRightMrValue.establish ||
      stateData.searchRightMrValue.review ||
      stateData.searchRightMrValue.state
    ) {
      dispatch(
        setMrOnchangeValue({
          establish: '',
          review: '',
          state: '',
        }),
      );
    }
    dispatch(setLeftDataPagination(1, false));
  };
};

export const closeMiddleMode = () => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_ROW_COL_SPAN,
      data: {
        left: '20',
        right: '4',
        middle: '0',
        middleState: false,
        previewDocId: '',
        rightOpen: false,
      },
    });
    dispatch({
      type: SEARCH_GET_MIDDLE_DATA,
      data: {},
    });
  };
};

export const getMiddleData = (value, headerModeStatus) => {
  return (dispatch) => {
    const previewValue = utils.getUrlParam({ name: 'inputtext', type: 'search' });
    dispatch({
      type: SEARCH_MIDDLE_LOADING,
      data: true,
    });
    exceed
      .fetch({
        api: 'search_root_codeup_preview',
        data: {
          is_dsl: headerModeStatus === 'grammar',
          keyword: decodeURIComponent(previewValue).trim(),
          doc_id: decodeURIComponent(value),
        },
      })
      .then((result) => {
        dispatch({
          type: SEARCH_MIDDLE_LOADING,
          data: false,
        });
        dispatch({
          type: SEARCH_GET_MIDDLE_DATA,
          data: result,
        });
      });
  };
};

export const setSearchLanguageValue = (value, flag, valueCount) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_SET_SEARCH_LANGUAGE,
      data: value,
    });
    dispatch(setLeftDataPagination(1, true));
    !flag && dispatch(getSearchInputData());
    !flag && dispatch(getsearchCountAndLanguage(false, valueCount));
  };
};

export const setMrOnchangeValue = (value) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_MR_STATE,
      data: value,
    });
    dispatch(setLeftDataPagination(1));
    dispatch(getSearchInputData());
    dispatch(getsearchCountAndLanguage(true));
  };
};

export const getOrgMember = (data) => {
  return async (dispatch) => {
    const value = await uilessRequest({
      url: `/api/members/search?filter=enabled&q=&pageSize=${data || 200}&_input_charset=utf-8`,
      method: 'GET',
    });
    dispatch({
      type: SEARCH_MR_SELECT_DATA,
      data: value.data.result,
    });
  };
};

export const getCodeStorehouse = (value) => {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'projects.exploreList',
        data: {
          page: 1,
          search: value || '',
          order_by: 'last_activity_at',
          group_by: '',
          per_page: 100,
          contains_sub_projects: '',
          archived: false,
        },
      })
      .then((result) => {
        result.shift();
        const arr = result.filter((va) => !va.demo_project);
        dispatch({
          type: SEARCH_CODE_STORE_HOUSE_DATA,
          data: arr,
        });
      });
  };
};

export const getCodeHouseValue = (value, flag) => {
  return (dispatch, getState) => {
    const stateData = getState().search.root;
    dispatch({
      type: SEARCH_CODE_STORE_HOUSE_TYPE_VALUE,
      data: value,
    });
    !flag && stateData.rowSpanCol.middleState && dispatch(closeMiddleMode());
    !flag && dispatch(setLeftDataPagination(1));
    !flag && dispatch(getSearchInputData());
    !flag && dispatch(getsearchCountAndLanguage(true));
  };
};

export const setRepoSelectValue = (value) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_CODE_REPO_SELECT_VALUE,
      data: value,
    });
    dispatch(setLeftDataPagination(1, true));
    dispatch(getSearchInputData());
    dispatch(getsearchCountAndLanguage(true));
  };
};

export const resetSetRepoSelectValue = (value) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_CODE_REPO_SELECT_VALUE,
      data: value,
    });
  };
};

export const setLeftData = (value) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_CODE_LEFT_LIST_DATA,
      data: value,
    });
  };
};

// 获取用户最近搜索历史
export function getSearchHistory() {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api: 'search.user_search_history',
      })
      .then((result) => {
        resolve(result);
      })
      .fail((err) => {
        reject(err);
      });
  });
}

// DSL统计接口
export function searchDslCount(data) {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api: 'search.dsl_count',
        data,
      })
      .then((result) => {
        resolve(result);
      })
      .fail((err) => {
        reject(err);
      });
  });
}

// 判断是否在grammer输入中 不调用统计接口防止语法报错
export const headerInputStatusChange = (value) => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_HEADER_INPUT_STATUS_CHANGE,
      data: value,
    });
  };
};

export const changeOneTip = (data) => {
  return (dispatch) => {
    dispatch({
      type: HEAD_INPUT_STRING_ONE_TIPS,
      data: data.length === 1,
    });
  };
};

export const closeErrorMessage = () => {
  return (dispatch) => {
    dispatch({
      type: SEARCH_DSL_ERROR_MESSAGE_CHANGE,
      data: null,
    });
  };
};

// 提交用户反馈
export function searchPostUserFeedBack(data) {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api: 'search.user_feed_back',
        data,
      })
      .then((result) => {
        resolve(result);
      })
      .fail((err) => {
        reject(err);
      });
  });
}
